var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp()
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
// var toast;
Page({

  /**
   * 页面的初始数据
   */
  data: {

    inorderhistory: [],
    waitPayOrder: [],
    inordering: [],
    // 
    neiorwai: 0,
    active: 0,
    //订单类型
    ordertypes: 0,

    time: 15 * 60 * 1000,
    // time: 3 * 1000,
    currtab: 1,
    swipertab: [
      { name: '已完成', index: 0 },
      { name: '待付款', index: 1 },
      { name: '已取消', index: 2 },
      { name: '出货中', index: 3 }],
    // 计算总数
    ordercount: {
      num: 0,
      money: 0.00
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //创建vant loading加载
    // toast = Toast.loading({
    //   duration: 0, // 持续展示 toast
    //   forbidClick: true,
    //   message: "加载中..."
    // });
    // wx.showLoading({
    //   title: '数据加载中',
    // })

    // util.request(api.OrderList).then(res => {
    //   util.request(api.PullOrdersList).then(res => {
    //   // console.log('res',res)
    //   if (res.data.errno == 0) {
    //     let orderlist = res.data.orderlist;
    //     console.log('orderlist:', orderlist)
    //     wx.setStorageSync('orderlist', orderlist)
    //   }
    // });
    // util.request(api.PullOrdersListIn).then(res => {
    //   // console.log('res',res)
    //   if (res.errno == 0) {
    //     // let orderlist = res.data.orderlist;
    //     // console.log('orderlist:', orderlist)
    //     // wx.setStorageSync('orderlistin', orderlist)
    //   }
    // })
    // wx.hideLoading()
  },

  onShow: function () {
    let that=this;
    // setInterval(function () {
    //   that.onShow();
    //   console.log("轮播请求1秒触发一次");
    // }, 1000)    //代表1秒钟发送一次请求
    wx.showToast({
      title: '数据加载',
      icon:'loading',
      success:res=>{
        setTimeout(() => {
        }, 1200)
      }
    })


    util.request(api.PullOrdersList,{
      openid:wx.getStorageSync('openid')
    },"POST").then(res => {
      console.log('res：', res)
      if (res.errno == 0) {
        let orderlist = res.data.orderlist;
        console.log('orderlist:', orderlist)
        wx.setStorageSync('orderlist', orderlist)
      }
    });
    // util.request(api.OrderListIn).then(res => {
    util.request(api.PullOrdersListIn,{
      openid:wx.getStorageSync('openid')
    },"POST").then(res => {
      console.log('res', res)
      if (res.errno == 0) {

        let orderlist = res.data.orderlist;
        console.log('orderlist:', orderlist)
        // if (orderlist.length != 0) {
        let orderings = orderlist.map(item => {
          console.log('item:', item)
          if ((item['order'].order_status != 2) && (item['order'].order_status != 1)) {
            console.log("item['order'].order_status", item['order'].order_status)
            console.log("item['order'].pay_status", item['order'].pay_status)
            return item
          }
        });
        let ordering=[]
        orderings=orderings.filter(item=>item)
        for(let s=0;s<orderings.length;s++){
          console.log('item:',orderings[s])
          ordering.push(orderings[s])
        }
        console.log('ordering:',ordering)
        util.request(api.GetRedis, { openid: wx.getStorageSync('openid'), order_sn:wx.getStorageSync('order_sn')}, "PUT").then(res => {
          console.log('res:',res)
          if (res.errno == 0) {
            let orderlists = res.data.orderlist;
            console.log('orderlist:', orderlists)
            if(orderlists){
              for(let i=0;i<orderlists.length;i++){
                console.log('orderlist:', orderlists[i][0])
                if (orderlists[i][0]['order']['send_type'] == 0) {
                  ordering.push(orderlists[i][0])
                }
              }
            }
            ordering = ordering.filter(item => item);
            // 已完成订单
        let orderfinish = orderlist.map(item => {
          if ((item['order'].order_status == 2) || (item['order'].order_status == 1)) {
            console.log("item['order'].order_status", item['order'].order_status)
            console.log("item['order'].pay_status", item['order'].pay_status)
            return item
          }
        });
        orderfinish = orderfinish.filter(item => item);
            setTimeout(() => {
              wx.setStorageSync('orderlistin', orderlist)
              that.setData({
                inordering: ordering,
                inorderhistory: orderfinish
              })
            }, 1000);
          }
        })
        // console.log('ordering:',ordering)
        
        
       
        
        
        // }

      }
    })

    // 加载待支付订单
    
    util.request(api.GetRedis, {
       openid: wx.getStorageSync('openid'),
       order_sn:wx.getStorageSync('order_sn')
      }, "POST").then(res => {
      console.log('res:', res)
      let ordering=[]
      if (res.errno == 0) {
        let orderlist = res.data.orderlist;
        if(orderlist){
          for(let i=0;i<orderlist.length;i++){
            console.log('orderlist:', orderlist[i][0])
            if (orderlist[i][0]['order']['send_type'] == 1) {
              ordering.push(orderlist[i])
            }
          }
        }
        that.setData({
          waitPayOrder: ordering
        })
      }
      that.setData({
        waitPayOrder: ordering
      })
    })


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 页面渲染完成
    this.getDeviceInfo()
    this.orderShow()
    this.alreadyShow()
    this.MakingShow()
    this.waitPayShow()
    this.lostShow()
  },

  getDeviceInfo: function () {
    let that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          deviceW: res.windowWidth,
          deviceH: res.windowHeight
        })
      }
    });

  },

  /**
  * @Explain：选项卡点击切换
  */
  tabSwitch: function (e) {
    var that = this
    if (this.data.currtab === e.target.dataset.current) {
      return false
    } else {
      that.setData({
        currtab: e.target.dataset.current
      })
    }
  },

  tabChange: function (e) {
    this.setData({ currtab: e.detail.current })
    this.orderShow()
  },

  orderShow: function () {
    let that = this
    switch (this.data.currtab) {
      case 0:
        wx.showToast({
          title: '加载中',
          icon:'loading',
          success:res=>{
            that.alreadyShow()
            wx.setTimeout(()=>{},1000)
          }
        })
        break
      case 1:
        
        
        wx.showToast({
          title: '加载中',
          icon:'loading',
          success:res=>{
            that.waitPayShow()
            setTimeout(() => {}, 1000);
          }
        })
        break
      case 2:
        
        wx.showToast({
          title: '加载中',
          icon:'loading',
          success:res=>{
            that.lostShow()
            setTimeout(()=>{},1000)
          }
        })
        break
      case 3:
        wx.showToast({
          title: '加载中',
          icon:'loading',
          success:res=>{
            that.MakingShow()
            setTimeout(()=>{},1000)
          }
        })
        break
    }
  },
  // 已完成
  alreadyShow: function () {
    let Orderlist = wx.getStorageSync('orderlist');
    // console.log('Orderlist:good',Orderlist[0]['good'])
    // console.log('Orderlist:order',Orderlist[0]['order'])
    let finshorder = Orderlist.map(item => {
      if (item['order'].order_status == 1 && item['order'].pay_status == 1) {
        console.log("item['order'].order_status", item['order'].order_status)
        console.log("item['order'].pay_status", item['order'].pay_status)
        return item
      }
    })
    // 删除里面的undefined
    finshorder = finshorder.filter(item => item)
    console.log('finshorder:', finshorder)
    this.setData({
      // alreadyOrder: [
      //   { name: "跃动体育运动俱乐部(圆明园店)", state: "交易成功", time: "2018-09-30 14:00-16:00",
      //  status: "已结束", url: "../../images/bad0.png", money: "132" }, 
      //   { name: "跃动体育运动俱乐部(圆明园店)", state: "交易成功", time: "2018-10-12 18:00-20:00", status: "未开始", url: "../../images/bad3.jpg", money: "205" }
      // ]
      alreadyOrder: finshorder
    })
  },
  //  待支付MakingShow waitPayShow lostShow
  waitPayShow: function () {
    // let that=this;
    // util.request(api.GetRedis,{openid:wx.getStorageSync('openid')},"POST").then(res=>{
    //   console.log('res:',res)
    //   if(res.errno==0){
    //     taht.setData({
    //       waitPayOrder: res.data.orderlist
    //     })
    //   }
    // })
    // 从数据库拿
    // let Orderlist= wx.getStorageSync('orderlist');
    // // console.log(Orderlist)
    // let waitorder = []
    // let waitPay = Orderlist.map(item => {
    //   if (item['order'].order_status == 0 && item['order'].pay_status == 0) {
    //     return item
    //   }
    // })
    // 删除里面的undefined
    // waitorder = waitPay.filter(item => item)
    // console.log(waitorder)
    // console.log('waitPay',waitPay)
    // let waitPayOrder =[{order_sn: "d0d5d5cc-9ac7-409a-823e-7e24cc0e3a85",
    //   order_status: 0,
    //   pay_status: 0,
    //   pid: 2,
    //   redatetime: "Thu, 03 Mar 2022 10:03:21 -0000",
    //   send_sn: "3dc28d7f-9a70-4983-ae10-cfdf2e51e27e",
    //   send_status: 0,
    //   send_type: 1,
    //   uid: 1,
    //   userid: "ocmg85A_-Bf-Gg_qkXthHHAXkqww",
    //   yuan_price: 12}]

  },
  //  已取消
  lostShow: function () {
    let Orderlist = wx.getStorageSync('orderlist');
    let lostorder = Orderlist.map(item => {
      if (item['order'].order_status == 2 && item['order'].pay_status == 0) {
        return item
      }
    })
    // 删除里面的undefined
    lostorder = lostorder.filter(item => item)
    console.log(lostorder)
    this.setData({
      lostOrder: lostorder
    })
  },
  // 出货中
  MakingShow() {
    let Orderlist = wx.getStorageSync('orderlist');
    // console.log(l)
    let Making = Orderlist.map(item => {
      // console.log(item)
      if (item['order'].order_status == 0 && item['order'].pay_status == 1) {

        return item
      }
    })
    // 删除里面的undefined
    Making = Making.filter(item => item)
    console.log(Making)
    this.setData({
      // waitPayOrder: [
      //   { name: "跃动体育运动俱乐部(圆明园店)", state: "待付款", time: "2018-10-14 14:00-16:00", status: "未开始", url: "../../images/bad1.jpg", money: "186" }
      // ],
      MakingOrder: Making
    })
  },
  // 倒计时函数
  finished(e) {
    // console.log('this.data.waitPayOrder:',this.data.waitPayOrder)
    // console.loge)
    let that=this;
    let order_sn = e.currentTarget.dataset.sn;
    let openid=wx.getStorageSync('openid');
    util.request(api.CancelOrder, {
      order_sn: order_sn,
      openid: openid
    }, "POST").then(res => {
      console.log(res)
      if(res.errno==0){
        wx.showToast({
          title: '取消订单成功',
          success:res=>{
            setTimeout(() => {
              that.onLoad()
              that.onShow()
              that.onReady()
            }, 1000);
          }
        })
      }else{
        console.log('res:',res)
      }
    })
  },
  // 支付取消的订单
  topay(e) {
    let that = this;
    console.log(e)
    let order_sn = e.currentTarget.dataset.sn;
    let addressid = e.currentTarget.dataset.addressid;
    let pid = e.currentTarget.dataset.pid;
    let waitPayOrder = this.data.waitPayOrder;
    
    console.log(waitPayOrder)

    wx.showModal({
      title: '提示',
      content: '是否确认支付？',
      success(res) {
        if (res.confirm) {
          util.request(api.UpdataOrders, {
            openid: wx.getStorageSync('openid'),
            order_sn: order_sn
          }, "POST").then(res => {
            wx.showModal({
              title: 'Tips:',
              content: '支付成功',
              success: function () {
                that.onLoad()
                that.onShow()
                setTimeout(res=>{
                  that.onReady()
                },1000)  
                
              }
            })
          }).catch(res => {
            wx.showModal({
              title: 'Tips:',
              content: '支付失败',
            })
          })


        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })




    // let patorder = waitPayOrder.map(item => {
    //   console.log(item)
    //   if (item['order'].order_sn != order_sn) {
    //     return item
    //   }
    // })





  },
  // 下拉加载数据
  onPullDownRefresh() {
    //1秒钟，关闭下拉刷新
    this.onLoad()
    this.onShow();
    
    setTimeout(() => {
      this.onReady();
      wx.stopPullDownRefresh()
    }, 1000)

  },
  // 取取货
  togethoods(e) {
    let that=this
    let oid = e.currentTarget.dataset.oid;
    console.log(oid);
    wx.showModal({
      title: '提示',
      content: '是否确认取货？',
      success: function (res) {
        if (res.confirm) {
          util.request(api.OrderEnter, {
            oid: oid
          }, "POST").then(res => {
            console.log('res:', res)
            wx.showToast({
              title: '取货成功',
              icon:'success',
              success:res=>{
                that.onLoad()
                that.onShow()
                setTimeout(() => {
                  that.onReady()
                }, 1000);
              }
            })
          }).catch(err => {
            console.log(err)
          })
        } else {
          wx.showToast({
            title: '取消取货'
          })
        }
      }
    })

    

  },
  //再来一单
  againorder(e) {
    let id = e.currentTarget.dataset.id;
    console.log(id);
    wx.switchTab({
      url: '/pages/catalog/index/index',
    })
  },
  // 店内使用切换懒
  onChange(event) {
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
  },
  // 取消支付
  toclose(e) {
    console.log(e)
    let that = this;
    
    let order_sn = e.currentTarget.dataset.sn;
    wx.showModal({
      title: 'Tips:',
      content: '你确定要订单关闭吗？',
      success: function (res) {
        if (res.confirm) {
          util.request(api.CancelOrder, {
            openid:wx.getStorageSync('openid'),
            order_sn: order_sn,
          }, "POST").then(res => {
            if(res.errno==0){
              wx.showToast({
                title: '取消成功',
                success:res=>{
                  setTimeout(() => {
                    that.onLoad()
                    that.onShow()
                    that.onReady()
                  }, 1000);
                }
              })  
          }
            
          })
        } else {
          console.log('取消')
        }
      }
    })


  },
  // 去评价

  toremark(e) {
    let id = e.currentTarget.dataset.id;
    let out = e.currentTarget.dataset.out;
    // console.log(id,out)÷
    wx.navigateTo({
      url: '/pages/order/remark/remark?id=' + id + '&out=' + out,
    })
  }
})

